Rust examples
Hello World
println!("Hello World!")
Sum of two numbers
fn main() { let s = sum(1, 2); println!("The sum of 1, 2 is {}", s); } fn sum(n1: i32, n2: i32) -> i32 { n1 + n2 }
Traits
pub trait Summary { fn summarize(&self) -> String; } pub struct Tweet { pub username: String, pub content: String, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{} {}", self.username, self.content) } } let tweet = Tweet { username: String::from("nerding_it"), content: String::from("Hello Twitter!"), }; println!("New tweet: {}", tweet.summarize());
Structures
struct User { name: String, }; let user = User { name: String::from("John"), }; println!("Hello {}", user.name);
If else
let i = 1; if (i > 0) { println!("Greater than 1"); } else { println!("Less than 1") }
Loop
let mut count = 0; loop { println!("Count is {}", count); count += 1; if count == 5 { break; } }
Process
use std::process::Command; fn main() { let output = Command::new("rustc") .arg("--version") .output().unwrap_or_else(|e| { panic!("failed to execute process: {}", e) }); if output.status.success() { let s = String::from_utf8_lossy(&output.stdout); print!("rustc succeeded and stdout was:\n{}", s); } else { let s = String::from_utf8_lossy(&output.stderr); print!("rustc failed and stderr was:\n{}", s); } }
Closure
let add = |n1: i32, n2: i32| -> i32 { n1 + n2}; println!("Add 1 2 is {}", add(1, 2));
Types
HashMap
use std::collections::HashMap; let mut people = HashMap::new(); people.insert("john", "India"); for (name, country) in people.iter() { println!("Hello {} from {}", name, country); }
Vectors
let vector: Vec<i32> = (0..10).collect(); println!("Collected (0..10) into {:?}", vector); let vector: Vec<i32> = vec![]; println!("Vector is {:?}", vector);